#!/usr/bin/python
from sys import argv, exit, stdin
from time import sleep, strftime
from select import select
from serial import Serial

color = {
    "purple" : "\033[95m",
    "yellow" : "\033[93m",
    "reset" : "\033[0m",
    "red" : "\033[91m",
    "bold" : "\033[1m",
    "green" : "\033[92m",
    "grey" : "\033[90m",
    "blue" : "\033[94m",
    "cyan" : "\033[96m",
    "white" : "\033[97m"
}

if len(argv) < 2:
    print "Usage: %s [USB interface]" %argv[0]
    exit()

def signal_handler(signal, frame):
        print "Break Signal received."
    exit(254)

s = Serial(port=argv[1],baudrate=115200) 
olddata = ""
while(True):
    sleep(.5)
    s.write("GLG\r")
#    s.write("GID\r")
    pdata = ""
    while s.inWaiting() > 0:
    	pdata += s.read(1)
    if pdata and not "GLG,,,,,,,,,,,," in pdata:
    		#debug# 
    		# print pdata
    		total_unk = len(pdata.split(","))-8
    		try: 
    			if total_unk is 5:
    				glg,sysid,band,unk,unk,sys,dept,chan,unk,unk,unk,unk,unk = pdata.split(",")
    			if total_unk is 6:
    				glg,sysid,band,unk,unk,sys,dept,chan,unk,unk,unk,unk,unk,unk = pdata.split(",")
    			if total_unk is 7:
    				glg,sysid,band,unk,unk,sys,dept,chan,unk,unk,unk,unk,unk,unk,unk = pdata.split(",")
    			if pdata != olddata:
    				print (color["bold"] + strftime("%H:%M:%S") + color["green"] + " - System: " + color["red"] + 
    					sys + color["green"] + " - Department: " + color["red"] + dept + color["green"] + 
    					" - Channel: " + color["red"] + chan + " (%s) " %sysid + color["reset"])
    				olddata = pdata
    		except:
    			pass

